package com.miplus.ccrm.core.utils;

import com.miplus.ccrm.common.JPubUtils;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

@Component
public class SpringContextUtil implements ApplicationContextAware {
    private static ApplicationContext applicationContext = null;

    @Override
    public void setApplicationContext(ApplicationContext context)
            throws BeansException
    {
        if (applicationContext == null)
        {
            applicationContext = context;
        }
    }

    public static ApplicationContext getApplicationContext()
    {
        return applicationContext;
    }

    public static <T> T getBean(Class<T> clazz)
    {
        return getApplicationContext().getBean(clazz);
    }

    public static final Object getBean(String beanName)
    {
        return getApplicationContext().getBean(beanName);
    }

    public static String getRequestHost()
    {
        HttpServletRequest h=((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
        return JPubUtils.getReqIpAddr(h);
    }
}
